package com.hotel.reservation.controller;

import com.hotel.reservation.po.Message;
import com.hotel.reservation.po.Reserve;
import com.hotel.reservation.po.User;
import com.hotel.reservation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "before/login";
    }

    @RequestMapping("/toRegister")
    public String toRegister(){
        return "before/register";
    }

    @RequestMapping("/login")
    public String login(@ModelAttribute User user, Model model, HttpSession session) {
        List<User> ans = userService.login(user);
        if (ans.size() <= 0) {
            model.addAttribute("msg", "账号密码错误");
            return "before/login";
        }
        session.setAttribute("user", ans.get(0));
        model.addAttribute("user",ans.get(0));
        System.out.println(ans.get(0).getUserId()+"ssss");
        return "before/main";
    }

    @RequestMapping("/register")
    public String register(@ModelAttribute User user, Model model) {
        int ans = userService.register(user);
        if (ans == -1) {
            model.addAttribute("msg","注册失败，用户已存在！");
            return "before/register";
        }
        model.addAttribute("msg","注册成功！");
        return "before/login";
    }

    @RequestMapping("/userInfo")
    public String userInfo(int userId,Model model){
        System.out.println(userId+"inUserInfo");
        List<User> user = userService.findOneUserById(userId);
        List<Message> messages = userService.findUserMessage(userId);
        List<Reserve> reserves = userService.findUserReserve(userId);
//        System.out.println(user+"user");
//        System.out.println(messages+"message");
//        System.out.println(reserves+"reserve");
        model.addAttribute("user",user.get(0));
        model.addAttribute("message",messages);
        model.addAttribute("reserve",reserves);
        return "before/userCenter";
    }

    @RequestMapping("/updateUser")
    public String updateUser(@ModelAttribute User user){
        System.out.println(user+"updateUser");
        int ans = userService.updateUser(user);
        System.out.println(ans+"updateUser");
        return "before/main";
    }
    @RequestMapping("/main")
    public String returnMain(){
        return "before/main";
    }
}
